package com.kevin.serial;

import com.kevin.Entity.Header;
import com.kevin.Entity.MessageRecord;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

@Slf4j
public class MessageRecorderDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        MessageRecord messageRecord = new MessageRecord();
        Header header = new Header();
        header.setSessionId(byteBuf.readLong());
        header.setOptCode(byteBuf.readByte());
        header.setBodyLength(byteBuf.readInt());
        messageRecord.setHeader(header);
        if(header.getBodyLength()>0){
            byte[] bodyContent = new byte[header.getBodyLength()];
            byteBuf.readBytes(bodyContent);
            /**
             * Java原生的对象流
             */
            ByteArrayInputStream bis=new ByteArrayInputStream(bodyContent);
            ObjectInputStream ios=new ObjectInputStream(bis);
            messageRecord.setBody(ios.readObject());//得到一个反序列化的数据

            log.info("反序列化出来的结果："+messageRecord);

        }else{
            messageRecord.setBody("");
        }
        list.add(messageRecord);
    }
}
